package net.ikenway.springboot.demo.Utils;

import net.ikenway.springboot.demo.Model.Entity.User;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * @author MasterKenway <zk@ikenway.net>
 * @Description
 * @date Created Date 12/15/2020
 */
@Component
public final class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringContextUtil.context == null) {
            SpringContextUtil.context = applicationContext;
        }
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static User getCurrentUser() {
        return (User) SecurityContextHolder.getContext().getAuthentication().getDetails();
    }
}